package com.donleo.security.controller;

import com.donleo.common.api.CommonResult;
import com.donleo.common.utils.CommonPath;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author liangd
 * date 2020-11-24 18:32
 * code 图片上传接口
 */
@RestController
@RequestMapping("/upload")
public class UploadController {

    @PostMapping("/img")
    public CommonResult uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return CommonResult.failed("上传失败");
        }
        //文件名称
        String fileName = file.getOriginalFilename();
        //允许上传文件名的后缀
        List<String> FILE_WHILE_EXT_LIST = Arrays.asList("JPG","PNG","JPEG","GIF");
        Assert.notNull(fileName,"File name can not be empty");
        String fileExtName = fileName.substring(fileName.lastIndexOf(".") + 1);
        if (FILE_WHILE_EXT_LIST.contains(fileExtName.toUpperCase())){
            //上传文件的位置
            //SAVE_PATH  E:/liangd/Java/stmg-front/src/main/webapp
            //IMG_PATH  /upload/
            String filePath = CommonPath.SAVE_PATH.getValue() + CommonPath.IMG_PATH.getValue();
            //全路径 E:/liangd/Java/stmg-front/src/main/webapp/upload/1.jpg
            File dest = new File(filePath + fileName);
            //数据库保存地址 /upload/1.jpg
            String imgPath = CommonPath.IMG_PATH.getValue() + fileName;
            try {
                file.transferTo(dest);
                return CommonResult.success(imgPath);
            } catch (IOException e) {
                return CommonResult.failed("上传失败");
            }
        }
        return CommonResult.failed("图片格式不正确");
    }
}
